<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>镇长登录 - 镇长日志</title>
    <!-- 移除了不存在的styles.css引用 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2E7D32',  // 绿色主题，符合农场/小镇风格
                        secondary: '#8D6E63', // 棕色，代表木材和土地
                        accent: '#FF9800',    // 橙色，代表活力
                        danger: '#C62828',
                        success: '#388E3C',
                        warning: '#F57C00',
                        dark: '#263238',
                        light: '#F5F5F5'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    backgroundImage: {
                        'game-bg': "url('https://picsum.photos/id/1002/1920/1080')", // 自然风景背景
                    }
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-game {
                background: linear-gradient(135deg, #2E7D32 0%, #8D6E63 100%);
            }
            .form-input-focus {
                @apply focus:ring-2 focus:ring-primary/30 focus:border-primary focus:outline-none;
            }
            .text-shadow {
                text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
            }
        }
    </style>
</head>
<body class="bg-game-bg bg-cover bg-fixed bg-center font-sans text-dark min-h-screen flex flex-col">
    <!-- 背景遮罩 -->
    <div class="fixed inset-0 bg-dark/50 z-0"></div>
    <!-- 导航栏 -->
    <nav id="navbar" class="bg-dark/80 text-white shadow-md backdrop-blur-sm z-10 sticky top-0">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-home text-primary text-2xl"></i>
                <a href="../../index.html" class="text-xl font-bold text-white text-shadow">镇长日志</a>
            </div>
            
            <div class="flex items-center space-x-4">
                <a href="../../index.html" class="text-white hover:text-primary transition-colors">返回游戏</a>
                <button id="mobile-menu-btn" class="md:hidden p-2 text-white hover:text-primary transition-colors">
                    <i class="fa fa-bars text-xl"></i>
                </button>
            </div>
        </div>
        
        <!-- 移动端菜单 -->
        <div id="mobile-menu" class="hidden md:hidden bg-dark/90 border-t border-white/10">
            <div class="container mx-auto px-4 py-3 flex flex-col space-y-4">
                <a href="../../index.html" class="text-white hover:text-primary transition-colors py-2 border-b border-white/10">游戏主页</a>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <main class="flex-1 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8 relative z-10">
        <div class="w-full max-w-md">
            <div class="bg-white/90 backdrop-blur-sm shadow-xl rounded-2xl overflow-hidden border border-white/20">
                <div class="p-6 sm:p-8">
                    <div class="text-center mb-6">
                        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 mb-4">
                            <i class="fa fa-user-circle text-primary text-3xl"></i>
                        </div>
                        <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-dark mb-2">欢迎回到小镇</h1>
                        <p class="text-gray-600">尊敬的镇长，请登录您的账号</p>
                    </div>
                    
                    <form id="login-form" class="space-y-4">
                        <div>
                            <label for="email" class="block text-sm font-medium text-gray-700 mb-1">联系邮箱</label>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <i class="fa fa-envelope text-primary/70"></i>
                                </div>
                                <input id="email" name="email" type="email" required
                                    class="block w-full pl-10 pr-3 py-3 border border-primary/30 rounded-lg shadow-sm form-input-focus"
                                    placeholder="请输入您的联系邮箱">
                            </div>
                            <p id="email-error" class="mt-1 text-sm text-danger hidden">邮箱格式不正确</p>
                        </div>
                        
                        <div>
                            <div class="flex items-center justify-between mb-1">
                                <label for="password" class="block text-sm font-medium text-gray-700">小镇密钥</label>
                                <a href="#" id="forgot-password-link" class="text-sm text-primary hover:text-primary/80 transition-colors">忘记密钥？</a>
                            </div>
                            <div class="relative">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <i class="fa fa-lock text-primary/70"></i>
                                </div>
                                <input id="password" name="password" type="password" required
                                    class="block w-full pl-10 pr-3 py-3 border border-primary/30 rounded-lg shadow-sm form-input-focus"
                                    placeholder="请输入您的小镇密钥">
                                <div class="absolute inset-y-0 right-0 pr-3 flex items-center">
                                    <button type="button" id="toggle-password" class="text-primary/70 hover:text-primary">
                                        <i class="fa fa-eye"></i>
                                    </button>
                                </div>
                            </div>
                            <p id="password-error" class="mt-1 text-sm text-danger hidden">密钥不能为空且长度至少为6位</p>
                        </div>
                        
                        <div class="flex items-center">
                            <input id="remember-me" name="remember-me" type="checkbox"
                                class="h-4 w-4 text-primary focus:ring-primary border-gray-300 rounded">
                            <label for="remember-me" class="ml-2 block text-sm text-gray-700">
                                记住镇长身份
                            </label>
                        </div>
                        
                        <div>
                            <button type="submit" id="login-btn"
                                class="w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-colors">
                                <i class="fa fa-sign-in mr-2"></i> 进入小镇
                            </button>
                        </div>
                    </form>
                    
                    <div class="mt-6">
                        <div class="relative">
                            <div class="absolute inset-0 flex items-center">
                                <div class="w-full border-t border-gray-300"></div>
                            </div>
                            <div class="relative flex justify-center text-sm">
                                <span class="px-2 bg-white/90 text-gray-500">便捷登录选项</span>
                            </div>
                        </div>
                        
                        <div class="mt-6 grid grid-cols-3 gap-3">
                            <button type="button" class="flex justify-center py-2 px-4 border border-primary/30 rounded-md shadow-sm bg-white/90 text-sm font-medium text-gray-700 hover:bg-primary/5 transition-colors">
                                <span class="sr-only">使用微信登录</span>
                                <i class="fa fa-weixin text-green-500"></i>
                            </button>
                            <button type="button" class="flex justify-center py-2 px-4 border border-primary/30 rounded-md shadow-sm bg-white/90 text-sm font-medium text-gray-700 hover:bg-primary/5 transition-colors">
                                <span class="sr-only">使用QQ登录</span>
                                <i class="fa fa-qq text-blue-500"></i>
                            </button>
                            <button type="button" class="flex justify-center py-2 px-4 border border-primary/30 rounded-md shadow-sm bg-white/90 text-sm font-medium text-gray-700 hover:bg-primary/5 transition-colors">
                                <span class="sr-only">使用微博登录</span>
                                <i class="fa fa-weibo text-red-500"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="mt-6 text-center text-sm">
                        <span class="text-gray-600">还没有小镇？</span>
                        <a href="register.html" class="font-medium text-primary hover:text-primary/80 transition-colors ml-1">
                            创建新小镇
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 忘记密码弹窗 -->
    <div id="forgot-password-modal" class="fixed inset-0 bg-black/50 z-50 hidden flex items-center justify-center p-4">
        <div class="bg-white/95 backdrop-blur-sm rounded-xl shadow-2xl max-w-md w-full max-h-[90vh] overflow-hidden">
            <div class="p-6 border-b flex justify-between items-center">
                <h3 class="font-bold text-lg text-primary">找回小镇密钥</h3>
                <button id="close-forgot-password" class="p-2 text-gray-500 hover:text-primary transition-colors">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-6">
                <form id="forgot-password-form" class="space-y-4">
                    <div>
                        <label for="reset-email" class="block text-sm font-medium text-gray-700 mb-1">联系邮箱</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-envelope text-primary/70"></i>
                            </div>
                            <input id="reset-email" name="email" type="email" required
                                class="block w-full pl-10 pr-3 py-3 border border-primary/30 rounded-lg shadow-sm form-input-focus"
                                placeholder="请输入您的联系邮箱">
                        </div>
                        <p id="reset-email-error" class="mt-1 text-sm text-danger hidden">请输入正确的邮箱地址</p>
                    </div>
                    
                    <!-- 密码显示区域 -->
                    <div id="password-display-area" class="hidden">
                        <label class="block text-sm font-medium text-gray-700 mb-1">您的小镇密钥</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-key text-primary/70"></i>
                            </div>
                            <input id="found-password" type="text" readonly
                                class="block w-full pl-10 pr-3 py-3 border border-primary/30 rounded-lg shadow-sm bg-gray-50"
                                placeholder="密钥将显示在这里">
                        </div>
                        <p class="mt-1 text-sm text-primary">请妥善保管您的密钥信息</p>
                    </div>
                    
                    <button type="submit" id="find-password-btn"
                        class="w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-colors">
                        <i class="fa fa-search mr-2"></i> 查询密钥
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- 通知弹窗 -->
    <div id="notification" class="fixed top-20 right-4 bg-white/90 backdrop-blur-sm shadow-lg rounded-lg p-4 max-w-xs transform translate-x-full transition-transform duration-300 z-50 hidden">
        <div class="flex items-start space-x-3">
            <div id="notification-icon" class="w-8 h-8 rounded-full flex items-center justify-center bg-primary/10 text-primary">
                <i class="fa fa-info-circle"></i>
            </div>
            <div class="flex-1">
                <h4 id="notification-title" class="font-medium text-dark"></h4>
                <p id="notification-message" class="text-gray-600 text-sm mt-1"></p>
            </div>
        </div>
    </div>

    <!-- 核心工具库 -->
    <script src="../../js/core.js"></script>
    
    <!-- 降级脚本 - 确保即使模块加载失败，基本功能也可用 -->
    <script>
        // 确保关键函数存在
        window.validateEmail = window.validateEmail || function(email) {
            const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return re.test(email);
        };
        
        window.validatePassword = window.validatePassword || function(password) {
            return password && password.length >= 6;
        };
        
        // 降级的更新头像函数
        window.updateAvatarByEmail = window.updateAvatarByEmail || function(email) {
            try {
                console.log('降级模式：更新头像', email);
                
                // 验证邮箱格式
                const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!re.test(email)) {
                    console.log('邮箱格式无效，不更新头像');
                    return;
                }
                
                // 使用默认头像
                let avatarUrl = './default-avatar.svg';
                
                // 尝试从用户数据中获取头像
                try {
                    const users = JSON.parse(localStorage.getItem('users') || '[]');
                    const user = users.find(u => u.email === email);
                    if (user && user.avatar) {
                        avatarUrl = user.avatar;
                        console.log('找到用户头像:', avatarUrl);
                    } else {
                        console.log('未找到用户头像，使用默认头像');
                    }
                } catch (e) {
                    console.warn('获取用户头像信息失败:', e);
                }
                
                // 更新头像容器
                const avatarContainers = document.querySelectorAll('.text-center.mb-6 > div');
                avatarContainers.forEach(container => {
                    try {
                        if (!container || !(container instanceof HTMLElement)) {
                            return;
                        }
                        
                        // 检查容器是否有头像元素
                        const hasImg = container.querySelector('img');
                        const hasIcon = container.querySelector('i.fa-user-circle');
                        
                        if (hasImg || hasIcon) {
                            // 移除原来的内容，添加新的img元素
                            container.innerHTML = '';
                            const img = document.createElement('img');
                            img.src = avatarUrl;
                            img.alt = '用户头像';
                            img.className = 'w-full h-full object-cover rounded-full';
                            
                            // 添加图片加载错误处理
                            img.onerror = function() {
                                console.warn('头像图片加载失败，使用备用图标');
                                container.innerHTML = '<i class="fa fa-user-circle text-primary text-3xl"></i>';
                            };
                            
                            container.appendChild(img);
                            console.log('降级模式：成功更新头像容器');
                        }
                    } catch (e) {
                        console.error('降级更新头像容器失败:', e);
                    }
                });
            } catch (e) {
                console.error('降级更新头像失败:', e);
            }
        };
    </script>
    <script>
        // 移动端菜单切换
        const mobileMenuBtn = document.getElementById('mobile-menu-btn');
        const mobileMenu = document.getElementById('mobile-menu');
        
        if (mobileMenuBtn && mobileMenu) {
            mobileMenuBtn.addEventListener('click', () => {
                mobileMenu.classList.toggle('hidden');
            });
        }

        // 密码显示切换
        const togglePassword = document.getElementById('toggle-password');
        const password = document.getElementById('password');
        
        if (togglePassword && password) {
            togglePassword.addEventListener('click', () => {
                const type = password.getAttribute('type') === 'password' ? 'text' : 'password';
                password.setAttribute('type', type);
                togglePassword.querySelector('i').classList.toggle('fa-eye');
                togglePassword.querySelector('i').classList.toggle('fa-eye-slash');
            });
        }

        // 忘记密码弹窗
        const forgotPasswordLink = document.getElementById('forgot-password-link');
        const forgotPasswordModal = document.getElementById('forgot-password-modal');
        const closeForgotPassword = document.getElementById('close-forgot-password');
        
        if (forgotPasswordLink && forgotPasswordModal) {
            forgotPasswordLink.addEventListener('click', (e) => {
                e.preventDefault();
                // 重置弹窗状态
                const passwordDisplayArea = document.getElementById('password-display-area');
                const foundPassword = document.getElementById('found-password');
                const resetEmailError = document.getElementById('reset-email-error');
                const resetEmail = document.getElementById('reset-email');
                
                if (passwordDisplayArea) passwordDisplayArea.classList.add('hidden');
                if (foundPassword) foundPassword.value = '';
                if (resetEmailError) resetEmailError.classList.add('hidden');
                if (resetEmail) resetEmail.value = '';
                
                // 显示弹窗
                forgotPasswordModal.classList.remove('hidden');
            });
        }
        
        if (closeForgotPassword && forgotPasswordModal) {
            closeForgotPassword.addEventListener('click', () => {
                forgotPasswordModal.classList.add('hidden');
            });
        }
        
        if (forgotPasswordModal) {
            forgotPasswordModal.addEventListener('click', (e) => {
                if (e.target === forgotPasswordModal) {
                    forgotPasswordModal.classList.add('hidden');
                }
            });
        }

        // 发送验证码按钮相关代码已移除，现在使用直接查询方式
        
        // 第三方登录按钮 - 功能开发中
        const thirdPartyLoginBtns = document.querySelectorAll('.wechat-login, .qq-login, .weibo-login');
        thirdPartyLoginBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                if (window.showNotification) {
                    window.showNotification('功能开发中', '第三方登录功能暂未开放，请使用账号密码登录', 'info');
                } else {
                    alert('功能开发中: 第三方登录功能暂未开放，请使用账号密码登录');
                }
            });
        })

        // 登录表单提交
        const loginForm = document.getElementById('login-form');
        
        if (loginForm) {
            loginForm.addEventListener('submit', (e) => {
                e.preventDefault();
                
                const email = document.getElementById('email').value;
                const password = document.getElementById('password').value;
                const emailError = document.getElementById('email-error');
                const passwordError = document.getElementById('password-error');
                const loginBtn = document.getElementById('login-btn');
                const rememberMe = document.getElementById('remember-me').checked;
                
                let isValid = true;
                
                // 验证邮箱
                if (!email || !(window.validateEmail && window.validateEmail(email))) {
                    if (emailError) {
                        emailError.textContent = '邮箱格式不正确';
                        emailError.classList.remove('hidden');
                    }
                    isValid = false;
                } else {
                    if (emailError) {
                        emailError.classList.add('hidden');
                    }
                }
                
                // 验证密码
                if (!(window.validatePassword && window.validatePassword(password))) {
                    if (passwordError) {
                        passwordError.classList.remove('hidden');
                    }
                    isValid = false;
                } else {
                    if (passwordError) {
                        passwordError.classList.add('hidden');
                    }
                }
                
                if (!isValid) return;
                
                // 禁用登录按钮防止重复提交
                if (loginBtn) {
                    loginBtn.disabled = true;
                    loginBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 登录中...';
                }
                
                // 模拟登录过程
                try {
                    // 模拟网络请求延迟
                    setTimeout(() => {
                        // 从localStorage获取用户数据
                        const users = JSON.parse(localStorage.getItem('users') || '[]');
                        // 检查用户是否存在并密码正确
                        const user = users.find(u => u.email === email && u.password === password);
                        
                        if (user) {
                            // 登录成功
                            // 确保用户对象包含必要的字段
                        // 计算注册时间（如果没有则从id计算，因为id是注册时间戳）
                        let registerDate = user.registerDate;
                        if (!registerDate && user.id) {
                            // 从id计算注册时间（id是Date.now()生成的时间戳）
                            const idTimestamp = parseInt(user.id);
                            if (!isNaN(idTimestamp)) {
                                registerDate = new Date(idTimestamp).toISOString();
                            }
                        }
                        // 如果还是没有，使用当前时间作为最后手段
                        if (!registerDate) {
                            registerDate = new Date().toISOString();
                        }
                        
                        const userData = {
                            id: user.id || Date.now().toString(),
                            username: user.username || email.split('@')[0],
                            email: user.email,
                            password: user.password, // 保存密码以便后续使用
                            avatar: user.avatar || '',
                            points: user.points || 0,
                            // 添加登录时间戳
                            lastLogin: new Date().toISOString(),
                            // 保留注册时间
                            registerDate: registerDate,
                            // 只保留lastCheckin字段当且仅当它是今天的日期，否则不设置
                            ...(user.lastCheckin === new Date().toDateString() ? { lastCheckin: user.lastCheckin } : {})
                        };
                            
                            // 保存用户信息到所有可能的存储位置，确保一致性
                            if (window.setUserInfo) {
                                window.setUserInfo(userData);
                            } else {
                                // 降级处理：直接保存到localStorage
                                localStorage.setItem('currentUser', JSON.stringify(userData));
                                localStorage.setItem('user', JSON.stringify(userData));
                                localStorage.setItem('userInfo', JSON.stringify(userData));
                            }
                            
                            // 记住我功能
                            if (rememberMe) {
                                localStorage.setItem('rememberedUser', JSON.stringify({
                                    email: user.email,
                                    password: user.password
                                }));
                            } else {
                                localStorage.removeItem('rememberedUser');
                            }
                            
                            // 强制更新用户界面，确保UI与用户状态同步
                            if (window.updateUserInfo) {
                                window.updateUserInfo();
                            }
                            
                            // 直接重定向，避免不必要的延迟
                            // 如果当前页面是login.html，跳转到index.html
                            if (window.location.pathname.endsWith('login.html')) {
                                window.location.href = 'index.html';
                            } else {
                                // 否则刷新当前页面以确保所有组件正确初始化
                                window.location.reload();
                            }
                        } else {
                            // 登录失败
                            if (emailError) {
                                emailError.textContent = '邮箱或密码错误';
                                emailError.classList.remove('hidden');
                            }
                            
                            if (loginBtn) {
                                loginBtn.disabled = false;
                                loginBtn.innerHTML = '<i class="fa fa-sign-in mr-2"></i> 进入小镇';
                            }
                        }
                    }, 1500);
                } catch (error) {
                    console.error('登录处理失败:', error);
                    
                    // 错误处理：尝试简单的登录流程作为降级方案
                    try {
                        // 即使在发生错误的情况下，也尝试创建一个基本的用户对象
                        const basicUser = {
                            id: Date.now().toString(),
                            username: email.split('@')[0],
                            email: email,
                            avatar: '',
                            points: 0
                        };
                        
                        // 保存基本用户信息到所有可能的存储位置
                        if (window.setUserInfo) {
                            window.setUserInfo(basicUser);
                        } else {
                            // 降级处理
                            localStorage.setItem('currentUser', JSON.stringify(basicUser));
                            localStorage.setItem('user', JSON.stringify(basicUser));
                            localStorage.setItem('userInfo', JSON.stringify(basicUser));
                        }
                        
                        // 强制更新用户界面
                        if (window.updateUserInfo) {
                            window.updateUserInfo();
                        }
                        
                        // 直接重定向
                        window.location.href = 'index.html';
                    } catch (e) {
                        // 如果降级方案也失败，显示最终错误
                        if (window.showNotification) {
                            window.showNotification('系统错误', '登录过程中发生严重错误，请稍后再试', 'error');
                        } else {
                            // 降级处理：使用alert
                            alert('系统错误: 登录过程中发生严重错误，请稍后再试');
                        }
                        
                        if (loginBtn) {
                            loginBtn.disabled = false;
                            loginBtn.innerHTML = '<i class="fa fa-sign-in mr-2"></i> 进入小镇';
                        }
                    }
                }
            });
        }
        
        // 监听用户信息变化事件
        window.addEventListener('storage', function(e) {
            // 当localStorage中的用户信息发生变化时，更新UI
            if (e.key === 'user' || e.key === 'userInfo' || e.key === 'currentUser') {
                if (window.updateUserInfo) {
                    window.updateUserInfo();
                }
            }
        });

        // 查询密码表单提交
        const forgotPasswordForm = document.getElementById('forgot-password-form');
        
        if (forgotPasswordForm) {
            forgotPasswordForm.addEventListener('submit', (e) => {
                e.preventDefault();
                
                const resetEmail = document.getElementById('reset-email').value;
                const resetEmailError = document.getElementById('reset-email-error');
                const findPasswordBtn = document.getElementById('find-password-btn');
                const passwordDisplayArea = document.getElementById('password-display-area');
                const foundPassword = document.getElementById('found-password');
                
                let isValid = true;
                
                // 验证邮箱
                if (!resetEmail || !(window.validateEmail && window.validateEmail(resetEmail))) {
                    if (resetEmailError) {
                        resetEmailError.textContent = '请输入正确的邮箱地址';
                        resetEmailError.classList.remove('hidden');
                    }
                    isValid = false;
                } else {
                    if (resetEmailError) {
                        resetEmailError.classList.add('hidden');
                    }
                }
                
                if (!isValid) return;
                
                // 禁用按钮防止重复提交
                if (findPasswordBtn) {
                    findPasswordBtn.disabled = true;
                    findPasswordBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 查询中...';
                }
                
                // 模拟网络请求延迟
                setTimeout(() => {
                    // 在本地存储中查找用户
                    const users = JSON.parse(localStorage.getItem('users') || '[]');
                    const user = users.find(u => u.email === resetEmail);
                    
                    if (user) {
                        // 找到用户，显示密码
                        if (passwordDisplayArea) {
                            passwordDisplayArea.classList.remove('hidden');
                        }
                        if (foundPassword) {
                            foundPassword.value = user.password;
                        }
                        
                        showNotification('查询成功', `已找到与邮箱关联的小镇密钥`, 'success');
                    } else {
                        // 未找到用户
                        if (resetEmailError) {
                            resetEmailError.textContent = '该邮箱未注册';
                            resetEmailError.classList.remove('hidden');
                        }
                    }
                    
                    // 恢复按钮状态
                    if (findPasswordBtn) {
                        findPasswordBtn.disabled = false;
                        findPasswordBtn.innerHTML = '<i class="fa fa-search mr-2"></i> 查询密钥';
                    }
                }, 1000);
            });
        }

        // 如果全局函数未加载完成，等待全局函数加载
        // 降级实现已在页面头部定义
        
        // 页面加载时初始化所有功能
        document.addEventListener('DOMContentLoaded', () => {
            console.log('全局工具函数加载脚本已执行');
            
            // 1. 尝试更新用户信息
            if (window.updateUserInfo) {
                window.updateUserInfo();
            } else {
                // 如果全局函数不可用，设置一个简单的定时器重试
                setTimeout(() => {
                    if (window.updateUserInfo) {
                        window.updateUserInfo();
                    }
                }, 500);
            }
            
            // 2. 自动填充记住的用户信息并更新头像
            const rememberedUser = localStorage.getItem('rememberedUser');
            if (rememberedUser) {
                try {
                    const user = JSON.parse(rememberedUser);
                    const emailInput = document.getElementById('email');
                    const passwordInput = document.getElementById('password');
                    const rememberMeCheckbox = document.getElementById('remember-me');
                    
                    // 确保用户对象有效
                    if (user && user.email) {
                        if (emailInput) {
                            emailInput.value = user.email;
                            // 如果填充了邮箱，更新头像（确保函数已加载）
                            if (window.updateAvatarByEmail) {
                                window.updateAvatarByEmail(user.email);
                            } else {
                                // 等待全局函数加载
                                setTimeout(() => {
                                    if (window.updateAvatarByEmail) {
                                        window.updateAvatarByEmail(user.email);
                                    }
                                }, 500);
                            }
                        }
                        if (passwordInput && user.password) passwordInput.value = user.password;
                        if (rememberMeCheckbox) rememberMeCheckbox.checked = true;
                    }
                } catch (e) {
                    console.error('自动填充用户信息失败:', e);
                }
            }
            
            // 3. 为邮箱输入框添加输入事件监听
            const emailInput = document.getElementById('email');
            if (emailInput) {
                emailInput.addEventListener('input', (e) => {
                    const email = e.target.value;
                    // 当用户停止输入300ms后再更新头像，避免频繁查询
                    if (emailInput._debounceTimer) {
                        clearTimeout(emailInput._debounceTimer);
                    }
                    emailInput._debounceTimer = setTimeout(() => {
                            if (window.updateAvatarByEmail) {
                                window.updateAvatarByEmail(email);
                            }
                        }, 300);
                });
            }
        });
    </script>
</body>
</html>